import { ElMessage } from 'element-plus'
import Chatmessage from './chatmessage/ChatMessage.vue';
import { reasonragIp } from '@/utils/zongID';
const BASE_URL = reasonragIp
import { ChatDotSquare,Comment } from '@element-plus/icons-vue'
export default {
    name: 'QueryInput',
    components: {
        Chatmessage,
        ChatDotSquare,
        Comment
    },
    props: {
        exampleFileSelected: {
            type: Boolean,
            default: false
        },
        files: {
            type: Array,
            default: () => []
        },
        resMsg: {
            type: String,
            default: ''
        },
        id: {
            type: String,
            default: ''
        },
        isUploading: {
            type: Boolean,
            default: false
        }
    },
    emits: ['update:exampleFileSelected', 'example-file-change', 'update:resMsg',
        'update:id',
        'update:is-uploading'],
    data() {
        return {
            query: '',
            netSearchEnabled: true,
            mrakdownSearchEnabled: true,
            quickQuestions: [
                '高血压怎么诊断？',
            ],
            resRaw: {},
            isSending: false,
            multi_hop: false,
            egfiles: [],
        }
    },
    methods: {
        async handleSubmit() {


            if (this.query.length === 0) {
                ElMessage.warning('请输入知识库相关问题');
                return;
            }
            if (this.files.length === 0) {
                ElMessage.warning('请选择文件');
                return;
            }
            if (this.resMsg === '') {
                ElMessage.warning('文件处理中');
                return;
            }
            if (this.isUploading) {
                ElMessage.warning("文件处理中，请稍等!");
                return;
            }
            // this.resRaw = { };
            this.resRaw = {
                search_display: '',
                answer: '',
                status: ''
            };
            this.isSending = true;
            const formData = new FormData();
            formData.append('question', this.query);
            formData.append('use_search', this.netSearchEnabled);
            formData.append('use_table_format', this.mrakdownSearchEnabled);
            formData.append('id', this.id);
            formData.append('multi_hop', this.multi_hop);
            try {
                const response = await fetch(`${BASE_URL}/api/rag-chat`, {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok || !response.body) {
                    throw new Error('Network response was not ok');
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let result = '';
                let isReading = true;
                while (isReading) {
                    const { done, value } = await reader.read();
                    if (done) {
                        isReading = false;
                        break;
                    }

                    const chunk = decoder.decode(value, { stream: true });
                    result += chunk;

                    const lines = result.split('\n');
                    result = lines.pop() || ''; // 保留最后一个不完整的行

                    for (const line of lines) {
                        if (line.trim() === '') continue; // 跳过空行
                        if (line.startsWith('data: ')) {
                            try {
                                const jsonStr = line.slice(6); // 移除 "data: " 前缀
                                const parsed = JSON.parse(jsonStr);
                                console.log("响应数据", parsed);



                                // this.resRaw = parsed;
                                // 修改
                                if (parsed.search_display) {
                                    this.resRaw.search_display = parsed.search_display;
                                }
                                if (parsed.answer) {
                                    this.resRaw.answer = parsed.answer;
                                }
                                if (parsed.status) {
                                    this.resRaw.status = parsed.status;
                                }




                            } catch (e) {
                                console.warn('JSON 解析失败:', line);
                            }
                        }
                    }

                    // 清空已处理的部分，防止重复解析
                    result = lines[lines.length - 1];
                }
            } catch (error) {
                console.error('请求失败:', error);
                ElMessage.error('网络错误，请检查网络连接！');
            } finally {
                this.isSending = false;
            }
        },
        async handleExampleFileChange(event) {
            const isChecked = event.target.checked;
            if (isChecked && this.files.length === 0) {
                // 如果勾选且文件选择框为空，则显示示例文件
                this.$emit('update:exampleFileSelected', true);
                this.$emit('update:exampleFileSelected', true);
                // 开始上传文件
                this.uploading = true;
                this.$emit('update:is-uploading', true);
                 const response = await fetch('/临床诊疗指南.pdf');
                // const response = await fetch('/30种家庭常用解酒方法.txt');
                const blob = await response.blob();
                const file = new File([blob], '《临床诊疗指南.pdf》', {
                // const file = new File([blob], '30种家庭常用解酒方法.txt》', {
                    type: 'application/pdf'
                });
                this.egfiles = [file];
                console.log(this.egfiles);
                const formData = new FormData();
                this.egfiles.forEach(file => {
                    formData.append('files', file);
                });

                try {
                    const response = await fetch(`${BASE_URL}/api/rag-uploadfile`, {
                        method: 'POST',
                        body: formData
                    });

                    if (response.ok) {
                        const res = await response.json();
                        console.log(res);
                        this.$emit('update:resMsg', res.message);
                        this.$emit('update:id', res.id);
                        ElMessage.success('文件上传成功');
                    } else {
                        throw new Error('上传失败');
                    }
                } catch (error) {
                    console.error('上传文件时出错:', error);
                    ElMessage.error('上传文件失败，请重试');
                } finally {
                    this.uploading = false;
                    this.$emit('update:is-uploading', false);
                }
            } else {
                // 如果取消勾选或文件选择框不为空，则不显示示例文件
                this.$emit('update:exampleFileSelected', false);
                // if (isChecked) {

                //     ElMessage.warning('请先清空已选择的文件');

                // }
            }
        },
        async handleQuickQuestion(question) {
            this.query = question;
            if (this.files.length === 0) {
                this.$emit('update:exampleFileSelected', true);
                // 开始上传文件
                this.uploading = true;
                this.$emit('update:is-uploading', true);
                 const response = await fetch('/临床诊疗指南.pdf');
                // const response = await fetch('/30种家庭常用解酒方法.txt');
                const blob = await response.blob();
                const file = new File([blob], '《临床诊疗指南.pdf》', {
                // const file = new File([blob], '30种家庭常用解酒方法.txt》', {
                    type: 'application/pdf'
                });
                this.egfiles = [file];
                console.log(this.egfiles);
                const formData = new FormData();
                this.egfiles.forEach(file => {
                    formData.append('files', file);
                });

                try {
                    const response = await fetch(`${BASE_URL}/api/rag-uploadfile`, {
                        method: 'POST',
                        body: formData
                    });

                    if (response.ok) {
                        const res = await response.json();
                        console.log(res);
                        this.$emit('update:resMsg', res.message);
                        this.$emit('update:id', res.id);
                        ElMessage.success('文件上传成功');
                    } else {
                        throw new Error('上传失败');
                    }
                } catch (error) {
                    console.error('上传文件时出错:', error);
                    ElMessage.error('上传文件失败，请重试');
                } finally {
                    this.uploading = false;
                    this.$emit('update:is-uploading', false);
                }
            }
        },
        handleClear() {
            this.query = '';
            // this.$emit('update:exampleFileSelected', false);
        }
    },

}
